const express = require("express");
const bodyParser = require("body-parser");

const app = express();
const mysql = require("mysql");
const conn = mysql.createConnection({
  host: "127.0.0.1",
  user: "root",
  password: "123456",

  database: "bishe",
  multipleStatements: true,
});

conn.connect((err) => {
  console.log(err, "如果为null 就是连接成功");
});

app.use(bodyParser.urlencoded({ extended: false }));

app.use(bodyParser.json());

app.all("*", function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Content-Type");
  res.header("Access-Control-Allow-Methods", "*");
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
});

//post请求
app.post("/login", (req, res) => {

  let { username, password } = req.body;
  const sql = "select * from bishetable where username=?";
  console.log(username);
  // 执行查找sql语句
  conn.query(sql, [username, password], (err, results) => {
    if (!results.length) {
      return res.json({
        code: 200,
        status: -1,
        msg: "登录失败，不存在该账户",
      });
    } else {
      console.log(results[0]["password"]);
      if (results[0]["password"] === password) {
        return res.json({
          status: 1,
          msg: "登录成功",
          data: { username: results[0].username, weight: results[0].weight },
          code: 200,
        });
      }
      return res.json({
        status: -2,
        msg: "密码错误",
        code: 200,
      });
    }
  });
});

//post请求
app.post("/register", (req, res) => {
  let { username, password } = req.body;
  /**
   *  注册的时候用户名是唯一的，不能与其他人的用户名一样
   *  在将信息写入数据库之前，要先检查用户名是否被占用
   */
  // 查询有无相同的用户名
  const sql = "select username from bishetable where username=?";
  // 执行查找sql语句
  conn.query(sql, username, (err, results) => {
    // sql语句执行失败
    console.log(err);
    // 执行成功，如果有数据，则说明有相同的用户名
    if (results.length === 1) return res.send("用户名被占用");
    // 执行成功，用户名没被占用
    // 定义新语句，增加用户
    const sqlStr = "insert into bishetable set ?";
    // 执行增加sql语句
    conn.query(sqlStr, { username, password }, (err, results) => {
      // 执行sql语句失败
      if (err) return res.send(err);
      // 执行sql语句成功 但影响行数不为1
      if (results.affectedRows !== 1) return res.send("用户注册失败！");
      // 执行成功，影响行数为1
      res.send({ code: 200, msg: "注册成功！" });
    });
  });
});


//post请求
app.post("/eidt", (req, res) => {
  let { username, weight } = req.body;
  const sql = "update bishetable set weight=? where username=?";

  // 执行查找sql语句
  conn.query(sql, [weight,username], (err, results) => {
   
console.log(err);
    
    if (err) return res.send(err);
    if (results.affectedRows !== 1) return res.send("修改失败！");
    res.send({ code: 200, msg: "修改成功！" });
  });
});
//监听
app.listen(4000, () => {
  console.log("4000端口已经启动。。。");
});
